<template>
  <div class="notification-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">消息中心</div>
      <div class="header-actions">
        <!-- 新增按钮 - 只对管理员显示 -->
        <el-button 
          v-if="isAdmin" 
          type="success" 
          @click="showAddDialog = true"
          style="margin-right: 10px;"
        >
          <el-icon><Plus /></el-icon>
          新增消息
        </el-button>
        <el-input
          v-model="searchQuery"
          placeholder="搜索消息..."
          style="width: 200px; margin-right: 10px;"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>
    </div>

    <!-- 表格容器 -->
    <div class="table-container">
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-radio-group v-model="filter" @change="handleFilterChange">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="unread">未读</el-radio-button>
        </el-radio-group>
        
        <div class="batch-actions" v-if="selected.length > 0">
          <el-button type="primary" size="small" @click="handleBatchMarkRead">
            批量标记已读
          </el-button>
          <el-button type="danger" size="small" @click="handleBatchDelete">
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 消息表格 -->
      <el-table
        :data="notifications"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="标题" min-width="150" />
        <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="isRead" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.isRead ? 'success' : 'danger'">
              {{ row.isRead ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button v-if="!row.isRead" size="small" type="primary" @click="handleMarkRead(row)">
              标记已读
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        style="margin: 20px 0; text-align: right;"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNum"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :page-sizes="[5, 10, 20, 50, 100]"
      />
    </div>

    <!-- 新增消息对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="新增消息"
      width="600px"
      :before-close="handleCloseDialog"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择消息类型" style="width: 100%;">
            <el-option label="系统消息" value="system" />
            <el-option label="审批消息" value="approval" />
            <el-option label="薪资消息" value="salary" />
            <el-option label="AI助手" value="ai" />
            <el-option label="个人资料" value="profile" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="接收用户" prop="userId">
          <el-select 
            v-model="addForm.userId" 
            placeholder="请选择接收用户（留空表示系统消息）" 
            style="width: 100%;"
            clearable
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userSearchLoading"
          >
            <el-option label="系统消息（所有用户可见）" :value="null" />
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="`${user.name} (${user.username})`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="addForm.title" placeholder="请输入消息标题" />
        </el-form-item>
        
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="addForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
          />
        </el-form-item>
        

      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleAddNotification" :loading="addLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useNotificationStore } from '@/stores/notification'
import { useUserStore } from '@/stores/user'

const notificationStore = useNotificationStore()
const userStore = useUserStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const notifications = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')
const filter = ref('all')
const selected = ref([])

// 新增消息相关
const showAddDialog = ref(false)
const addLoading = ref(false)
const addFormRef = ref()
const userSearchLoading = ref(false)
const userOptions = ref([])

// 新增表单
const addForm = reactive({
  type: '',
  userId: null,
  title: '',
  content: ''
})

// 表单验证规则
const addFormRules = {
  type: [
    { required: true, message: '请选择消息类型', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入消息标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' },
    { min: 1, max: 500, message: '内容长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

// 计算属性 - 判断是否为管理员
const isAdmin = computed(() => {
  return userStore.userInfo?.role === 'HR_ADMIN' || userStore.userInfo?.role === 'ADMIN'
})

// 搜索用户
const searchUsers = async (query) => {
  if (query.length < 2) {
    userOptions.value = []
    return
  }
  
  try {
    userSearchLoading.value = true
    const response = await axios.get('/users/search', {
      params: { keyword: query }
    })
    userOptions.value = response.data || []
  } catch (error) {
    console.error('搜索用户失败:', error)
    userOptions.value = []
  } finally {
    userSearchLoading.value = false
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  showAddDialog.value = false
  // 重置表单
  Object.assign(addForm, {
    type: '',
    userId: null,
    title: '',
    content: ''
  })
  addFormRef.value?.clearValidate()
}

// 新增消息
const handleAddNotification = async () => {
  try {
    await addFormRef.value.validate()
    addLoading.value = true
    
    const notificationData = {
      type: addForm.type,
      userId: addForm.userId,
      title: addForm.title,
      content: addForm.content
    }
    
    await axios.post('/api/notifications', notificationData)
    ElMessage.success('消息发送成功')
    handleCloseDialog()
    fetchNotifications() // 刷新列表
  } catch (error) {
    console.error('新增消息失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('新增消息失败，请重试')
    }
  } finally {
    addLoading.value = false
  }
}

// 获取消息分页列表
const fetchNotifications = async () => {
  try {
    loading.value = true
    const params = {
      page: pageNum.value - 1,
      size: pageSize.value,
      keyword: searchQuery.value || undefined
    }
    
    if (filter.value === 'unread') {
      params.isRead = false
    }
    
    const response = await axios.get('/api/notifications', { params })
    const data = response.data || {}
    notifications.value = Array.isArray(data.content) ? data.content : []
    total.value = typeof data.totalElements === 'number' ? data.totalElements : 0
    loading.value = false
  } catch (error) {
    console.error('获取消息列表失败:', error)
    ElMessage.error('获取消息列表失败，请重试')
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pageNum.value = 1
  fetchNotifications()
}

// 重置
const handleReset = () => {
  searchQuery.value = ''
  filter.value = 'all'
  pageNum.value = 1
  fetchNotifications()
}

// 筛选变化
const handleFilterChange = () => {
  pageNum.value = 1
  fetchNotifications()
}

// 分页变化
const handlePageChange = (page) => {
  pageNum.value = page
  fetchNotifications()
}

// 页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  pageNum.value = 1
  fetchNotifications()
}

// 选择变化
const handleSelectionChange = (rows) => {
  selected.value = rows.map(r => r.id)
}

// 标记已读
const handleMarkRead = async (row) => {
  try {
    await notificationStore.markAsRead([row.id])
    ElMessage.success('已标记为已读')
    fetchNotifications()
  } catch (error) { ElMessage.error('操作失败') }
}

// 删除消息
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    await notificationStore.deleteNotifications([row.id])
    ElMessage.success('删除成功')
    fetchNotifications()
  } catch (error) { if (error !== 'cancel') { ElMessage.error('删除失败') } }
}

// 批量标记已读
const handleBatchMarkRead = async () => {
  try {
    await notificationStore.markAsRead(selected.value)
    ElMessage.success('批量标记已读成功')
    fetchNotifications()
  } catch (error) { ElMessage.error('操作失败') }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selected.value.length} 条消息吗？`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    await notificationStore.deleteNotifications(selected.value)
    ElMessage.success('批量删除成功')
    fetchNotifications()
  } catch (error) { if (error !== 'cancel') { ElMessage.error('删除失败') } }
}

// 跳转链接
const handleGoLink = (row) => {
  if (row.link) {
    router.push(row.link)
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

// 获取类型标签
const getTypeLabel = (type) => {
  const typeMap = {
    'system': '系统',
    'approval': '审批',
    'salary': '薪资',
    'ai': 'AI助手',
    'profile': '个人资料'
  }
  return typeMap[type] || type
}

// 获取类型标签颜色
const getTypeTag = (type) => {
  const tagMap = {
    'system': 'primary',
    'approval': 'warning',
    'salary': 'success',
    'ai': 'info',
    'profile': 'default'
  }
  return tagMap[type] || 'default'
}

onMounted(fetchNotifications)
</script>

<style scoped>
.notification-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 15px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-container {
  flex: 1;
  padding: 0 20px 20px;
  background-color: #fff;
  overflow-y: auto;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.batch-actions {
  display: flex;
  gap: 10px;
}

/* 调整表格行高 */
:deep(.el-table__row) {
  height: 50px;
}

/* 调整表格头部样式 */
:deep(.el-table__header) {
  font-weight: bold;
  background-color: #f5f7fa;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f0f8ff !important;
}
</style>